package com.wzxy.wzinfo.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wzxy.wzinfo.entiry.User;
import com.wzxy.wzinfo.service.impl.UserService;

@Controller
@RequestMapping("User")
public class UserController {
	
	@Autowired
	private UserService userService;
	private String view = "main";
	
	@PostMapping("login")
	public String login(User user ,HttpServletResponse response , HttpSession session){
		User u = userService.login(user);
		if(u!=null){
			session.setAttribute("login_user", u);
			view = "main";
		}
		return view;
	}
	
	@GetMapping(value="/logout")
	public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
	    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
	    if (auth != null){    
	        new SecurityContextLogoutHandler().logout(request, response, auth);
	    }
	    return "redirect:/login?logout";//You can redirect wherever you want, but generally it's a good practice to show login screen again.
	}
	
	@GetMapping("openpage")
	public String toPage(String page){
		return page;
	}
}
